package com.newegg.whois.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.newegg.whois.model.DomainInfo;
import de.malkusch.whoisServerList.api.v1.DomainListFactory;
import de.malkusch.whoisServerList.api.v1.model.DomainList;
import de.malkusch.whoisServerList.api.v1.model.domain.Domain;
import de.malkusch.whoisServerList.api.v1.model.domain.TopLevelDomain;

public class DomainUtil {
	
	static DomainList doaminList = new DomainListFactory().build();
	
	public static DomainInfo getDomainInfo(String name){
		name = name.replace("http://", "").replace("https://", "");
		ArrayList<String> dp = new ArrayList<>(Arrays.asList(name.split("\\.")));
		Domain domain = null;
		while(dp.size() > 0){
			String suffix = String.join(".", dp);
			domain = getDomain(suffix);
			if(domain != null){
				DomainInfo info = new DomainInfo();
				if(!name.equals(domain.getName())){
					String profix = name.replace("." + domain.getName(), "");
					if(profix.indexOf(".") == -1){
						info.setDomain(profix);
					}else{
						String dm = profix.substring(profix.lastIndexOf(".") + 1);
						String subDomain = profix.substring(0, profix.lastIndexOf("."));
						info.setDomain(dm);
						info.setSubdomain(subDomain);
					}
				}
				info.setTld(domain.getName());
				List<String> servers = new ArrayList<>();
				domain.getWhoisServers().forEach(s->{
					servers.add(s.getHost());
				});
				info.setWhoisServers(servers);
				return info;
			}else{
				dp.remove(0);
			}
		}
		return null;
	}
	
	static Domain getDomain(String suffix) {
		for (TopLevelDomain top : doaminList.getDomains()) {
			if(top.getName().equalsIgnoreCase(suffix)){
				return top;
			}
		}
		for (TopLevelDomain top : doaminList.getDomains()) {
			for (Domain domain : top.getDomains()) {
				if(domain.getName().equalsIgnoreCase(suffix) && domain.getWhoisServers().size() > 0){
					return domain;
				}
			}
		}
		return null;
	}
	
	public static void main(String[] args) {
		System.out.println(getDomainInfo("www.newegg.com"));
	}
}
